﻿using JsonConversion;
using Newtonsoft.Json;
using RTracker.Areas.Recruitment.Models.Shift;
using RTracker.Models.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace RTracker.Areas.Recruitment.Controllers
{
    public class ShiftController : RTracker.Controllers.AppBaseController
    {
        //
        // GET: /Shift/

        [HttpPost]
        public ActionResult Save(GShift oGShift)
        {

            try
            {
                //check if Model validation is true if not then return detail view with errors
                if (true)//ModelState.IsValid
                {
                    //call CheckSession to get session status
                    string SessionState = CheckSessionState();
                    //check if session state is ok else return false status to view.
                    if (SessionState == CAppConstants.SessionSuccess)
                    {
                        bool _userPermission = false;

                        if (oGShift.Shift.OrganizationId == 0)
                        {
                            _userPermission = checkUserPermission(CUserPermissionsConstants.OrganizationCreate);
                        }
                        else
                        {
                            _userPermission = checkUserPermission(CUserPermissionsConstants.OrganizationUpdate);
                        }


                        if (_userPermission)
                        {
                            CShift objCShift = new CShift();
                            objCShift = oGShift.Shift;
                            MShift objMShift = new MShift();

                            if (objCShift.ShiftId == 0)
                            {
                                objCShift.OrganizationId = CurrentUserSession.OrganizationId;
                                oGShift.Status = objMShift.CreateShift(AuthenticationContext, ref objCShift);
                            }
                            else
                            {
                                oGShift.Status = objMShift.UpdateShift(AuthenticationContext, ref objCShift);
                            }
                        }
                        else
                        {
                            oGShift.Status = new CStatus();
                            oGShift.Status.Success = false;
                            oGShift.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        oGShift.Status = new CStatus();
                        oGShift.Status.Success = false;
                        oGShift.Status.StatusDetails = SessionState;
                    }
                }
                else
                {
                    oGShift.Status = new CStatus();
                    oGShift.Status.Success = false;
                    oGShift.Status.StatusDetails = CAppErrorsConstants.ValidationFail;
                }
            }
            catch (Exception ex)
            {
                oGShift.Status = new CStatus();
                oGShift.Status.Success = false;
                oGShift.Status.StatusDetails = ex.Message;
            }
            return Json(oGShift);
        }

        [HttpPost]
        public ActionResult GetDetails(int pnId)
        {
            GShift objGShift = new GShift();

            objGShift.Status = new CStatus();

            objGShift.Shift = new CShift();

            objGShift.Shift.ShiftId = pnId;

            CShift objCShift = new CShift();

            ViewBag.IsDisabled = true;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (0 == pnId)
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationCreate))
                        {
                            //here we will append new form to create new organisation
                            ViewBag.IsNew = true;
                            objGShift.Status.Success = true;
                            objGShift.Status.StatusDetails = CAppConstants.DetailSuccess;
                        }
                        else
                        {
                            objGShift.Status.Success = false;
                            objGShift.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationDetailView))
                        {
                            //here we will append new for detail 
                            MShift objMShift = new MShift();

                            ViewBag.IsNew = false;

                            objCShift.ShiftId = objGShift.Shift.ShiftId;

                            objGShift.Status = objMShift.GetShiftDetail(AuthenticationContext, ref objCShift);

                            //get the different admin names from their id from the application user list
                            objCShift.CreatedByName = GetFullName(objCShift.CreatedBy);
                            objCShift.ModifiedByName = GetFullName(objCShift.ModifiedBy);
                            objCShift.SoftLockedByName = GetFullName(objCShift.SoftLockedBy);
                            objCShift.HardLockedByName = GetFullName(objCShift.HardLockedBy);


                            if (!CheckLocksByOther(objCShift))
                            {
                                ViewBag.IsDisabled = false;
                            }
                            if (objGShift.Status.Success == true)
                            {
                                objGShift.Shift = objCShift;
                            }
                        }
                        else
                        {
                            objGShift.Status = new CStatus();
                            objGShift.Status.Success = false;
                            objGShift.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                }
                else
                {
                    objGShift.Status = new CStatus();
                    objGShift.Status.Success = false;
                    objGShift.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGShift.Status = new CStatus();
                objGShift.Status.Success = false;
                objGShift.Status.StatusDetails = ex.Message;
            }

            return PartialView("_detail", objGShift);
        }

        [HttpPost]
        public ActionResult Delete(string pstrIds)
        {
            GShift objGShift = new GShift();

            objGShift.Shift = new CShift();

            objGShift.Shift.ShiftIds = pstrIds;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;

                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (pstrIds != "")
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationDelete))
                        {
                            //code to delete the record
                            MShift objMShift = new MShift();

                            CShift objCShift = new CShift();

                            objCShift.ShiftIds = objGShift.Shift.ShiftIds;

                            objGShift.Status = objMShift.DeleteShift(AuthenticationContext, ref objCShift);

                            if (objGShift.Status.Success == true)
                            {
                                objGShift.Shift = objCShift;
                            }
                        }
                        else
                        {
                            objGShift.Status = new CStatus();
                            objGShift.Status.Success = false;
                            objGShift.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        objGShift.Status = new CStatus();
                        objGShift.Status.Success = false;
                        objGShift.Status.StatusDetails = CAppErrorsConstants.NotValidRequest;
                    }
                }
                else
                {
                    objGShift.Status = new CStatus();
                    objGShift.Status.Success = false;
                    objGShift.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGShift.Status = new CStatus();
                objGShift.Status.Success = false;
                objGShift.Status.StatusDetails = ex.Message;
            }

            return Json(objGShift.Status);
        }

        [HttpPost]
        public ActionResult GridRefresh(int pnId, string pstrSortOn, string pstrSortType, int pnPageNo, int pnPageSize, string pstrSearch, string pstrSearchOn, int pnOrgId = 1)
        {

            GShift objGShift = new GShift();
            try
            {
                if (pstrSearch == null || pstrSearchOn == null)
                {
                    pstrSearch = "";
                    pstrSearchOn = "";
                }

                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    CShift objCShift = new CShift() { ShiftId = pnId, SortOn = pstrSortOn, SortType = pstrSortType, PageNumber = pnPageNo, RowSize = pnPageSize, Search = pstrSearch, SearchOn = pstrSearchOn, OrganizationId = pnOrgId };


                    //check if current users organization id is 1 then it means it is superUser then need to get all organizations list
                    if (CurrentUserSession.OrganizationId == pnOrgId)
                    {

                        MShift objMShift = new MShift();

                        objGShift = objMShift.GetShiftGridList(objCShift, AuthenticationContext);

                        if (objGShift.LstShift != null)
                        {
                            if (objGShift.LstShift.Count > 0)
                            {
                                objGShift.LstShift.ForEach(VacancyStatus =>
                                {
                                    VacancyStatus.CreatedByName = GetFullName(VacancyStatus.CreatedBy);
                                    VacancyStatus.ModifiedByName = GetFullName(VacancyStatus.ModifiedBy);
                                    VacancyStatus.SoftLockedByName = GetFullName(VacancyStatus.SoftLockedBy);
                                    VacancyStatus.HardLockedByName = GetFullName(VacancyStatus.HardLockedBy);
                                });
                            }
                        }

                        // if status is true get object of the record to be selected in the list.
                        // first of all we will check the if given record exist in the list.
                        // if given record exist then get the object of that record.
                        // if record not exist in the list then select the first record of the list.
                        if (objGShift.Status.Success)
                        {
                            // if status is true get object of the record to be selected in the list.
                            // first of all we will check the if given record exist in the list.
                            // if given record exist then get the object of that record.
                            // if record not exist in the list then select the first record of the list.
                            if (objGShift.LstShift != null)
                            {
                                CShift objSelectedCShift = objGShift.LstShift.Where(m => m.ShiftId == pnId).DefaultIfEmpty(objGShift.LstShift[0]).First();

                                // check if record is not already hard locked or softlocked
                                if (objSelectedCShift.IsSoftLocked == false && objSelectedCShift.IsHardLocked == false)
                                {
                                    objSelectedCShift.CreatedBy = CurrentUserSession.UserId;
                                    objGShift.Status = objMShift.SetShiftSoftLock(AuthenticationContext, objSelectedCShift);
                                    if (objGShift.Status.Success)
                                    {
                                        // updating the list with softlock details
                                        objGShift.LstShift.Where(m => m.ShiftId == objSelectedCShift.ShiftId).First().IsSoftLocked = true;
                                        objGShift.LstShift.Where(m => m.ShiftId == objSelectedCShift.ShiftId).First().SoftLockedBy = CurrentUserSession.UserId;
                                    }
                                }
                            }


                        }

                        ViewBag.bPagingEnabled = true;
                        ViewBag.bSearchEnabled = true;
                        ViewBag.bNewDeleteEnabled = true;
                        ViewBag.bCopyPasteEnabled = false;
                    }
                    //else get detail for current users organization and show it in grid.
                    else
                    {
                        objCShift = new CShift() { OrganizationId = CurrentUserSession.OrganizationId };

                        MShift objMShift = new MShift();

                        objGShift.Status = objMShift.GetShiftDetail(AuthenticationContext, ref objCShift);

                        objGShift.LstShift.Add(objCShift);
                        //set view bag variables for pagging, new, delete and search.
                        ViewBag.bPagingEnabled = false;
                        ViewBag.bSearchEnabled = false;
                        ViewBag.bNewDeleteEnabled = false;
                        ViewBag.bCopyPasteEnabled = false;
                    }

                    // check if status is true
                    if (objGShift.Status.Success)
                    {
                        if (objGShift.LstShift != null)
                        {
                            if (objGShift.LstShift.Count > 0)
                            {
                                objGShift.LstShift[0].SortOn = pstrSortOn;
                                objGShift.LstShift[0].SortType = pstrSortType;
                            }
                        }
                        // set the values of sort on and sort type in the view bag.
                        ViewBag.SortType = pstrSortType;
                        ViewBag.SortOn = pstrSortOn;
                        ViewBag.CurrentUser = CurrentUserSession.UserId;
                    }
                }
                else
                {
                    //set status to false and its detail.
                    objGShift.Status = new CStatus();
                    objGShift.Status.Success = false;
                    objGShift.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {
                // catch the exceptions in any step ,if any 
                //set status to false and its detail as exception message.
                objGShift.Status = new CStatus();
                objGShift.Status.Success = false;
                objGShift.Status.StatusDetails = ex.Message;
            }
            ViewBag.CurrentUser = CurrentUserSession.UserId;
            //check if status is true then return list view(partial view of list) else return object with false status.
            if (objGShift.Status.Success)
                return PartialView("_list", objGShift);
            else
                return Json(objGShift);
        }

        [HttpPost]
        public ActionResult ReleaseSoftLock(int pnId)
        {
            GShift objGShift = new GShift();

            objGShift.Shift = new CShift();

            objGShift.Shift.ShiftId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {

                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (0 == pnId)
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationUpdate))
                        {
                            //here we will append new form to create new organisation
                            ViewBag.IsNew = true;
                            objGShift.Status.Success = true;
                        }
                        else
                        {
                            objGShift.Status.Success = false;
                            objGShift.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        MShift objMShift = new MShift();
                        objGShift.Shift.CreatedBy = CurrentUserSession.UserId;
                        objGShift.Status = objMShift.ReleaseShiftSoftLock(AuthenticationContext, objGShift.Shift);
                    }
                }
                else
                {
                    objGShift.Status = new CStatus();
                    objGShift.Status.Success = false;
                    objGShift.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGShift.Status = new CStatus();
                objGShift.Status.Success = false;
                objGShift.Status.StatusDetails = ex.Message;
            }

            return Json(objGShift.Status);
        }

        [HttpPost]
        public ActionResult SetHardLock(int pnId)
        {
            GShift objGShift = new GShift();

            objGShift.Shift = new CShift();

            objGShift.Shift.ShiftId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    MShift objMShift = new MShift();
                    objGShift.Shift.CreatedBy = CurrentUserSession.UserId;
                    objGShift.Status = objMShift.SetShiftHardLock(AuthenticationContext, objGShift.Shift);
                }
                else
                {
                    objGShift.Status = new CStatus();
                    objGShift.Status.Success = false;
                    objGShift.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGShift.Status = new CStatus();
                objGShift.Status.Success = false;
                objGShift.Status.StatusDetails = ex.Message;
            }
            return Json(objGShift.Status);
        }

        [HttpPost]
        public ActionResult ReleaseHardLock(int pnId)
        {
            GShift objGShift = new GShift();

            objGShift.Shift = new CShift();

            objGShift.Shift.ShiftId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    MShift objMShift = new MShift();
                    objGShift.Shift.CreatedBy = CurrentUserSession.UserId;
                    objGShift.Status = objMShift.ReleaseShiftHardLock(AuthenticationContext, objGShift.Shift);
                }
                else
                {
                    objGShift.Status = new CStatus();
                    objGShift.Status.Success = false;
                    objGShift.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGShift.Status = new CStatus();
                objGShift.Status.Success = false;
                objGShift.Status.StatusDetails = ex.Message;
            }

            return Json(objGShift.Status);
        }
    }
}
